#include "drawwidget.h"
#include <QDebug>
#include <QPainter>

#define PI (3.1415926)

DrawWidget::DrawWidget(QWidget *parent)
    : QWidget(parent)
{
    // 对窗体背景色的设置
    setAutoFillBackground(true);
    setPalette(QPalette(Qt::black));

    pixmap_ = new QPixmap(size());
    pixmap_->fill(Qt::white);
}

DrawWidget::~DrawWidget()
{

}

void DrawWidget::paintEvent(QPaintEvent *)
{
    // 将pixmap绘制到widget
    QPainter painter(this); // 设置QPaintDevice为widget
    painter.drawPixmap(QPoint(0, 0), *pixmap_);

    // coords
    QPoint orig(10, 10);
    QPoint xEnd(200, 10);
    QPoint yEnd(10, 200);

    painter.setPen(QPen(Qt::black));
    painter.drawLine(orig, xEnd);
    painter.drawLine(orig, yEnd);

    QPoint xArrowPoints[3] =
    {
        QPoint(xEnd.x(), xEnd.y() - 5),
        QPoint(xEnd.x(), xEnd.y() + 5),
        QPoint(xEnd.x() + 10, xEnd.y()),
    };

    painter.setBrush(QBrush(Qt::black, Qt::SolidPattern));
    painter.drawPolygon(xArrowPoints, 3);

    QPoint yArrowPoints[3] =
    {
        QPoint(yEnd.x() - 5, yEnd.y()),
        QPoint(yEnd.x() + 5, yEnd.y()),
        QPoint(yEnd.x(), yEnd.y() + 10),
    };

    painter.drawPolygon(yArrowPoints, 3);
}

void DrawWidget::mousePressEvent(QMouseEvent *event)
{
    QVector<QPoint> line;
    lines_.append(line);

    QVector<QPoint> &lastLine = lines_.last();
    lastLine.append(event->pos());
}

void DrawWidget::mouseMoveEvent(QMouseEvent *event)
{
    QVector<QPoint> &lastLine = lines_.last();
    lastLine.append(event->pos());

    // 在鼠标移动中，完成向pixmap中绘图的工作
    QPainter painter;
    painter.begin(pixmap_); // 指定pixmap为QPaintDevice

    for (int i = 0; i < lines_.size(); ++i)
    {
        const QVector<QPoint> &line = lines_.at(i);

        for (int j = 0; j < line.size() - 1; ++j)
        {
            painter.drawLine(line.at(j), line.at(j + 1));
        }
    }

    painter.end();

    update(); // 调用update会触发paint event
}

void DrawWidget::mouseReleaseEvent(QMouseEvent *event)
{
    width_ = width();
    height_ = height();
}

void DrawWidget::resizeEvent(QResizeEvent *event)
{
    int deltax = (width() - width_) / 2;
    int deltay = (height() - height_) / 2;

    delete pixmap_;

    pixmap_ = new QPixmap(size());
    pixmap_->fill(Qt::white);

    QPainter painter;
    painter.begin(pixmap_);

    for (int i = 0; i < lines_.size(); ++i)
    {
        const QVector<QPoint> &line = lines_.at(i);

        for (int j = 0; j < line.size() - 1; ++j)
        {
            painter.drawLine(line.at(j) + QPoint(deltax, deltay), line.at(j + 1) + QPoint(deltax, deltay));
        }
    }

    painter.end();

    QWidget::resizeEvent(event);
}
